<?php

namespace app\api\server;


use app\common\exception\FailedException;
use app\common\library\RedisKey;
use app\common\library\Show;
use GatewayWorker\Lib\Gateway;
use support\Redis;

class ClientServer extends BaseServer
{
    public static function bind($params)
    {
        try {
            $adminUser = [
                'id' => 1,
                'username' => "测试username",
                'nickname' => "测试nickname",
                'avatar' => "测试avatar",
            ];
            self::GatewayInit();
            if (!Gateway::isOnline($params['client_id'])) {
                throw new FailedException('无效的client_id');
            }
            Gateway::bindUid($params['client_id'], $adminUser['id']);
            Gateway::joinGroup($params['client_id'], 'every');//加入分组
            Redis::setEx(RedisKey::clientBind($params['client_id']), config('client.bind_time') + 10, 1);
            return Show::success(['uid' => $adminUser['id']]);
        } catch (\Throwable $exception) {
            return Show::error($exception->getMessage());
        }
    }


    public static function sendToGroup($group, $type, $data)
    {
        try {
            self::GatewayInit();
            Gateway::sendToGroup($group, json_encode(['type' => $type, 'data' => $data]));
            return Show::success();
        } catch (\Throwable $exception) {
            return Show::error($exception->getMessage());
        }
    }

    public static function sendToUser($uid, $type, $data)
    {
        try {
            self::GatewayInit();
            Gateway::sendToUid($uid, json_encode(['type' => $type, 'data' => $data]));
            return Show::success();
        } catch (\Throwable $exception) {
            return Show::error($exception->getMessage());
        }
    }

    public static function getUidListByGroup($Group)
    {
        try {
            self::GatewayInit();
            return Show::success(Gateway::getUidListByGroup($Group));
        } catch (\Throwable $exception) {
            return Show::error($exception->getMessage());
        }
    }
}